<template>
  <div class="task-page">
    <div class="page-header">
      <h1>任务管理</h1>
      <div class="header-actions">
        <el-button type="primary" plain @click="handleTemplateManager">
          <el-icon><Setting /></el-icon>
          模板管理
        </el-button>
        <el-button type="primary" @click="showAddTaskDialog">
          <el-icon><Plus /></el-icon>
          添加任务
        </el-button>
      </div>
    </div>

    <el-tabs v-model="activeTab" class="task-tabs">
      <el-tab-pane label="进行中的任务" name="active">
        <div v-if="activeTasks.length === 0" class="empty-state">
          <el-empty description="暂无进行中的任务" />
        </div>
        <div v-else class="task-list">
          <TaskCard
            v-for="task in activeTasks"
            :key="task.id"
            :task="task"
            @show-detail="showTaskDetail"
            @archive="handleArchiveTask"
          />
        </div>
      </el-tab-pane>

      <el-tab-pane label="已完成的任务" name="completed">
        <div v-if="completedTasks.length === 0" class="empty-state">
          <el-empty description="暂无已完成的任务" />
        </div>
        <div v-else class="task-list">
          <CompletedTaskCard
            v-for="task in completedTasks"
            :key="task.id"
            :task="task"
            @show-detail="showTaskDetail"
          />
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 添加任务对话框 -->
    <AddTaskDialog
      v-model="addTaskDialogVisible"
      @success="handleTaskAdded"
    />

    <!-- 任务详情对话框 -->
    <TaskDetailDialog
      v-model="taskDetailDialogVisible"
      :task="selectedTask"
      @deleted="handleTaskDeleted"
    />

    <!-- 模板管理对话框 -->
    <TemplateManagerDialog
      v-model="templateManagerDialogVisible"
      :templates="taskTemplates"
      @save="handleTemplateSave"
      @delete="handleTemplateDelete"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { Plus, Document, Setting } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getSkillList, updateSkill, createSkill } from '@/api/skill'
import TaskCard from '@/pages/admin/components/TaskCard.vue'
import CompletedTaskCard from '@/pages/admin/components/CompletedTaskCard.vue'
import AddTaskDialog from '@/pages/admin/components/AddTaskDialog.vue'
import TaskDetailDialog from '@/pages/admin/components/TaskDetailDialog.vue'
import TemplateManagerDialog from '@/pages/admin/components/TemplateManagerDialog.vue'

// 状态
const activeTab = ref('active')
const activeTasks = ref([])
const completedTasks = ref([])
const addTaskDialogVisible = ref(false)
const taskDetailDialogVisible = ref(false)
const templateManagerDialogVisible = ref(false)
const selectedTask = ref(null)

// 任务模板数据
const taskTemplates = ref([
  {
    id: 1,
    name: '理论学习模板',
    template: {
      skillName: '理论学习/',
      description: '通过系统学习掌握理论知识',
      stages: [
        {
          name: '基础学习',
          nodes: [
            { name: '阅读教材' },
            { name: '观看视频' },
            { name: '做笔记' }
          ]
        },
        {
          name: '深入理解',
          nodes: [
            { name: '整理知识点' },
            { name: '绘制思维导图' },
            { name: '总结重点' }
          ]
        }
      ]
    }
  },
  {
    id: 2,
    name: '实践开发模板',
    template: {
      skillName: '实践开发/',
      description: '通过实际项目开发提升技能',
      stages: [
        {
          name: '项目准备',
          nodes: [
            { name: '需求分析' },
            { name: '技术选型' },
            { name: '环境搭建' }
          ]
        },
        {
          name: '开发实现',
          nodes: [
            { name: '功能开发' },
            { name: '代码优化' },
            { name: '测试调试' }
          ]
        }
      ]
    }
  },
  {
    id: 3,
    name: '专项训练模板',
    template: {
      skillName: '专项训练/',
      description: '针对特定技能进行专项训练',
      stages: [
        {
          name: '基础训练',
          nodes: [
            { name: '基础动作' },
            { name: '标准姿势' },
            { name: '基础技巧' }
          ]
        },
        {
          name: '进阶训练',
          nodes: [
            { name: '组合动作' },
            { name: '实战应用' },
            { name: '技巧提升' }
          ]
        }
      ]
    }
  }
])

// 生命周期钩子
onMounted(async () => {
  await fetchTasks()
})

// 方法
const fetchTasks = async () => {
  try {
    const response = await getSkillList({
      pageNum: 1,
      pageSize: 100
    })
    const tasks = response.data.data.map(task => ({
      ...task,
      stages: JSON.parse(task.stages)
    }))
    console.log('tasks',tasks)
    activeTasks.value = tasks.filter(task => task.isCompleted === 1)
    completedTasks.value = tasks.filter(task => task.isCompleted === 2)
  } catch (error) {
    console.error('获取任务列表失败:', error)
    ElMessage.error('获取任务列表失败')
  }
}

const showAddTaskDialog = () => {
  addTaskDialogVisible.value = true
}

const handleTaskAdded = async () => {
  await fetchTasks()
  // ElMessage.success('任务添加成功')
}

const showTaskDetail = (task) => {
  selectedTask.value = task
  taskDetailDialogVisible.value = true
}

const handleArchiveTask = async (task) => {
  try {
    await updateSkill({
      id: task.id,
      completedAt: new Date().toISOString()
    })
    
    await fetchTasks()
    ElMessage.success('任务已归档')
  } catch (error) {
    console.error('归档任务失败:', error)
    ElMessage.error('归档任务失败')
  }
}

const handleTaskDeleted = async () => {
  await fetchTasks()
  // ElMessage.success('任务已删除')
}

// 处理模板管理
const handleTemplateManager = () => {
  templateManagerDialogVisible.value = true
}

// 处理模板保存
const handleTemplateSave = (templateData) => {
  if (templateData.id) {
    // 更新现有模板
    const index = taskTemplates.value.findIndex(t => t.id === templateData.id)
    if (index !== -1) {
      taskTemplates.value[index] = templateData
    }
  } else {
    // 添加新模板
    templateData.id = Date.now() // 使用时间戳作为临时ID
    taskTemplates.value.push(templateData)
  }
}

// 处理模板删除
const handleTemplateDelete = (templateId) => {
  const index = taskTemplates.value.findIndex(t => t.id === templateId)
  if (index !== -1) {
    taskTemplates.value.splice(index, 1)
  }
}
</script>

<style scoped>
.task-page {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.task-tabs {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.task-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-top: 20px;
}

.empty-state {
  padding: 40px 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .task-page {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .page-header h1 {
    font-size: 20px;
  }

  .task-tabs {
    padding: 16px;
  }

  .header-actions {
    width: 100%;
    flex-direction: column;
  }

  .header-actions .el-button {
    width: 100%;
  }
}
</style> 